package com.utils;

import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sys.location.entity.Location;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 公共路线接口方法，计算实际距离。
 */
@Slf4j
public class MapDistanceUtil {

	private static final String HOSTARR = "http://restapi.amap.com/v3/geocode/regeo";
	private static final String HOST = "https://restapi.amap.com/v3/distance";
// private static final String HOST = "http://122.114.79.163:7770/v3/distance";
	private static final String KEY = "761e73b6188fb868feee5b558dcbcd7a";

	/**
	 * 参数:（出发点数组、目的点） 格式：经度,纬度 返回: { "status": "1", "info": "OK", "infocode":
	 * "10000", "results": [{ //结果数组 "origin_id": "1", //第一个起点 "dest_id": "1", //目的地
	 * "distance": "261278", //距离（米） "duration": "14280" //预计时间（秒） }] }
	 */
	public static String mapDistanceMethod(String[] origins, String destination) {
		String responseEntity = null;
		for (int i = 0; i < 5 && responseEntity == null; i++) {
			responseEntity = mapDistance(origins, destination);
		}
		return responseEntity;
	}
	
	
	
	public static Location getLocation(String lon,String lat) {
		Location view=new Location();
		List<NameValuePair> list = new LinkedList<>();
		list.add(new BasicNameValuePair("key", KEY));
		list.add(new BasicNameValuePair("output", "JSON"));
		list.add(new BasicNameValuePair("location", lon+","+lat));
		String responseEntity = null;
		String addr = "";
		try {
			HttpGet httpGet = new HttpGet(new URIBuilder(HOSTARR).setParameters(list).build());
			httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
			HttpResponse response = HttpClients.createDefault().execute(httpGet);
			responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
			JSONObject jsonObject = JSON.parseObject(responseEntity);
			
			JSONObject streetNumber=jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent").getJSONObject("streetNumber");
			JSONObject addressComponent=jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent");
			
			
			String number=streetNumber.getString("number");
			String street=streetNumber.getString("street");
			String country=addressComponent.getString("country");
			String province=addressComponent.getString("province");
			String district=addressComponent.getString("district");
			String township=addressComponent.getString("township");
			String towncode=addressComponent.getString("towncode");
			String adcode=addressComponent.getString("adcode");
			
			
			System.out.println("国家："+country+",省："+province+",区："+district+",乡(镇)："+township+",路："+street+",号："+number+",行政区划代码:"+towncode+",区域代码："+adcode);
			view.setNumber(number);
			view.setStreet(street);
			view.setCountry(country);
			view.setTownship(township);
			view.setAdcode(adcode);
			view.setTowncode(towncode);
			view.setProvince(province);
			view.setDistrict(district);
			view.setExtendInfo(jsonObject.toString());
			
			addr = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent").getJSONObject("building")
					.getString("name");
			if (addr.equals("[]")) {
				addr = jsonObject.getJSONObject("regeocode").getString("formatted_address");
				if (addr.indexOf("省") > 0) {
					addr = addr.substring(addr.indexOf("省") + 1, addr.length());
				}
				if (addr.indexOf("市") > 0) {
					addr = addr.substring(addr.indexOf("市") + 1, addr.length());
				}
			}
//				System.out.println("-------响应结果-------\n" + addr);
		} catch (Exception e) {
			if (e instanceof ConnectTimeoutException) {
				System.out.println("-------请求超时-------");
			} else {
				System.out.println("-------数据获取失败-------"+e);
			}
		}
		return view;
	}
	
	
	
	
	
	
	
	
	
	

	public static String getLocationAddr(String location) {
		List<NameValuePair> list = new LinkedList<>();
		list.add(new BasicNameValuePair("key", KEY));
		list.add(new BasicNameValuePair("output", "JSON"));
		list.add(new BasicNameValuePair("location", location));
		String responseEntity = null;
		String addr = "";
		try {
			HttpGet httpGet = new HttpGet(new URIBuilder(HOSTARR).setParameters(list).build());
			httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
			HttpResponse response = HttpClients.createDefault().execute(httpGet);
			responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
			JSONObject jsonObject = JSON.parseObject(responseEntity);
//			System.out.println(jsonObject);
			
			JSONObject streetNumber=jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent").getJSONObject("streetNumber");
			JSONObject addressComponent=jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent");
			String number=streetNumber.getString("number");
			String street=streetNumber.getString("street");
			String country=addressComponent.getString("country");
			String province=addressComponent.getString("province");
			String district=addressComponent.getString("district");
			String township=addressComponent.getString("township");
			String towncode=addressComponent.getString("towncode");
			String adcode=addressComponent.getString("adcode");
			
			System.out.println("国家："+country+",省："+province+",区："+district+",乡(镇)："+township+",路："+street+",号："+number+",行政区划代码:"+towncode+",区域代码："+adcode);
			
			addr = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent").getJSONObject("building")
					.getString("name");
			if (addr.equals("[]")) {
				addr = jsonObject.getJSONObject("regeocode").getString("formatted_address");
				if (addr.indexOf("省") > 0) {
					addr = addr.substring(addr.indexOf("省") + 1, addr.length());
				}
				if (addr.indexOf("市") > 0) {
					addr = addr.substring(addr.indexOf("市") + 1, addr.length());
				}
			}
//				System.out.println("-------响应结果-------\n" + addr);
		} catch (Exception e) {
			if (e instanceof ConnectTimeoutException) {
				System.out.println("-------请求超时-------");
			} else {
				e.printStackTrace();
			}
		}
		return addr;
	}

	private static String mapDistance(String[] origins, String destination) {
		StringBuilder originBuilder = new StringBuilder();
		for (int i = 0; i < origins.length; i++) {
			originBuilder.append(origins[i]);
			if (i < origins.length - 1) {
				originBuilder.append("|");
			}
		}
		List<NameValuePair> list = new LinkedList<>();
		list.add(new BasicNameValuePair("key", KEY));
		list.add(new BasicNameValuePair("output", "JSON"));
		list.add(new BasicNameValuePair("origins", originBuilder.toString()));
		list.add(new BasicNameValuePair("destination", destination));
		String responseEntity = null;
		try {
			HttpGet httpGet = new HttpGet(new URIBuilder(HOST).setParameters(list).build());
			httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
			HttpResponse response = HttpClients.createDefault().execute(httpGet);
			responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
			System.out.println("-------距离测量响应结果-------\n" + responseEntity);
		} catch (Exception e) {
			if (e instanceof ConnectTimeoutException) {
				System.out.println("-------请求超时-------");
			} else {
				e.printStackTrace();
			}
		}
		return responseEntity;
	}

	public static void main(String[] args) throws InterruptedException {
//getLocationAddr("113.242439,35.1863620");
		
		System.out.println(getLocationAddr("121.50664,31.16492"));
//		System.out.println(getLocationAddr("113.242439,35.1863620"));
// String[] origins = new String[]{"116.481028,39.989643", "114.481028,39.989643", "115.481028,39.989643"};
// String destination = "114.465302,40.004717";
// for (int i = 0; i < 100; i++) {
// MapDistanceUtil.mapDistanceMethod(origins, destination);
// System.out.println("---------第" + i + "次请求");
// Thread.sleep(200);
// }
	}
}